{% extends "base.html" %}

{% block title %}个人中心 - 墨韵图书共享平台{% endblock %}

{% block content %}
<style>
.avatar-container {
    text-align: center;
    margin-bottom: 20px;
}
.avatar-preview, .default-avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    margin: 0 auto;
    display: block;
    object-fit: cover;
}
.default-avatar {
    background-color: #6c757d;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 48px;
}
.user-avatar-lg {
    width: 120px;
    height: 120px;
}
.user-avatar-small {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}
.default-avatar-small {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #e9ecef;
    color: #6c757d;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1rem;
}
.avatar-upload {
    margin-top: 15px;
}
.avatar-upload-tip {
    font-size: 12px;
    color: #6c757d;
}
#avatar-preview-container {
    margin-top: 15px;
    display: none;
}
#avatar-preview-image {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    margin: 0 auto;
    display: block;
    object-fit: cover;
    border: 2px solid #ddd;
}
.avatar-preview-buttons {
    margin-top: 10px;
}
</style>

<div class="container mt-4">
    <div class="row">
        <!-- 左侧个人信息 -->
        <div class="col-md-4">
            <div class="card ink-card mb-4">
                <div class="card-body text-center">
                    <div class="avatar-container">
                        <!-- 当前头像 -->
                        <div id="current-avatar">
                            {% if current_user.avatar and current_user.avatar != 'default.png' %}
                            <img src="{{ url_for('static', filename='avatars/' + current_user.avatar) }}" 
                                class="avatar-preview" alt="{{ current_user.username }}">
                            {% else %}
                            <div class="default-avatar user-avatar-lg">
                                {{ current_user.username[0] }}
                            </div>
                            {% endif %}
                        </div>
                        
                        <!-- 头像预览区域 -->
                        <div id="avatar-preview-container">
                            <img id="avatar-preview-image" src="" alt="头像预览">
                            <div class="avatar-preview-buttons">
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="cancelAvatarPreview()">
                                    <i class="fas fa-times"></i> 取消
                                </button>
                                <button type="button" class="btn btn-sm btn-primary" onclick="confirmAvatarUpload()">
                                    <i class="fas fa-check"></i> 确认
                                </button>
                            </div>
                        </div>
                        
                        <!-- 隐藏的表单 -->
                        <form id="avatar-form" action="{{ url_for('update_profile') }}" method="POST" enctype="multipart/form-data" style="display:none;">
                            <input type="file" name="avatar" id="avatar-input">
                        </form>
                        
                        <!-- 选择头像按钮 -->
                        <div class="avatar-upload mt-3">
                            <input type="file" id="avatar-select" accept="image/*" onchange="previewAvatar(this)" style="display: none;">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="document.getElementById('avatar-select').click()">
                                <i class="fas fa-camera"></i> 更换头像
                            </button>
                            <div class="avatar-upload-tip mt-1">支持 JPG、PNG、GIF 格式</div>
                        </div>
                    </div>
                    <h4>{{ current_user.username }}</h4>
                    <p class="text-muted">
                        {% if current_user.is_teacher %}
                        <i class="fas fa-chalkboard-teacher"></i> 教师
                        {% else %}
                        <i class="fas fa-user-graduate"></i> 学生
                        {% endif %}
                    </p>
                    <p class="text-muted">
                        <i class="fas fa-id-card"></i> {{ current_user.student_id }}
                    </p>
                    <form action="{{ url_for('update_profile') }}" method="POST">
                        <div class="mb-3">
                            <label for="bio" class="form-label">个人简介</label>
                            <textarea class="form-control ink-input" id="bio" name="bio" rows="3">{{ current_user.bio or '' }}</textarea>
                        </div>
                        <button type="submit" class="btn btn-primary ink-btn">
                            <i class="fas fa-save"></i> 保存修改
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- 右侧内容 -->
        <div class="col-md-8">
            <!-- 通知列表 -->
            <div class="card ink-card mb-4">
                <div class="card-header ink-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">通知</h5>
                    <button id="mark-all-read-btn" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-check-double"></i> 全部标为已读
                    </button>
                </div>
                <div class="list-group list-group-flush">
                    {% for notification in notifications %}
                    <div class="list-group-item {% if not notification.is_read %}list-group-item-primary{% endif %} notification-item" 
                         data-notification-id="{{ notification.id }}" role="button">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-1">{{ notification.title }}</h6>
                                <p class="mb-1">{{ notification.content }}</p>
                                <small class="text-muted">{{ notification.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
                            </div>
                            {% if notification.type == 'invite' and not notification.is_read %}
                            <div class="btn-group">
                                <form action="{{ url_for('respond_to_invitation', notification_id=notification.id) }}" method="POST" class="d-inline">
                                    <input type="hidden" name="action" value="accept">
                                    <button type="submit" class="btn btn-sm btn-success">
                                        <i class="fas fa-check"></i> 接受
                                    </button>
                                </form>
                                <form action="{{ url_for('respond_to_invitation', notification_id=notification.id) }}" method="POST" class="d-inline">
                                    <input type="hidden" name="action" value="reject">
                                    <button type="submit" class="btn btn-sm btn-danger">
                                        <i class="fas fa-times"></i> 拒绝
                                    </button>
                                </form>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    {% else %}
                    <div class="list-group-item text-center text-muted">
                        暂无通知
                    </div>
                    {% endfor %}
                </div>
            </div>

            <!-- 收藏内容 - 使用Tabs -->
            <div class="card ink-card mb-4">
                <div class="card-header ink-header">
                    <!-- Tab 导航 -->
                    <ul class="nav nav-tabs card-header-tabs" id="favoritesTab" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="favorite-books-tab" data-bs-toggle="tab" data-bs-target="#favoriteBooks" type="button" role="tab" aria-controls="favoriteBooks" aria-selected="true">
                                <i class="fas fa-book"></i> 收藏的图书
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="favorite-posts-tab" data-bs-toggle="tab" data-bs-target="#favoritePosts" type="button" role="tab" aria-controls="favoritePosts" aria-selected="false">
                                <i class="fas fa-comments"></i> 收藏的帖子
                            </button>
                        </li>
                    </ul>
                </div>
                <div class="card-body">
                    <!-- Tab 内容 -->
                    <div class="tab-content" id="favoritesTabContent">
                        <!-- 收藏的图书 Tab -->
                        <div class="tab-pane fade show active" id="favoriteBooks" role="tabpanel" aria-labelledby="favorite-books-tab">
                            {% if favorite_books %}
                            <div class="row row-cols-1 row-cols-md-2 g-3">
                                {% for book in favorite_books %}
                                <div class="col">
                                    <div class="card h-100 book-card" style="border-radius: 8px; overflow: hidden;">
                                        <div class="d-flex">
                                            <div class="flex-shrink-0" style="width: 80px; height: 120px;">
                                                {% if book.cover_path %}
                                                <img src="{{ url_for('static', filename='covers/' + book.cover_path) }}" 
                                                     alt="{{ book.title }}" class="img-fluid h-100 w-100" style="object-fit: cover;"
                                                     onerror="handleImageError(this)">
                                                {% else %}
                                                <div class="bg-light h-100 d-flex align-items-center justify-content-center">
                                                    <i class="fas fa-book fa-2x text-muted"></i>
                                                </div>
                                                {% endif %}
                                            </div>
                                            <div class="flex-grow-1 p-2 d-flex flex-column">
                                                <h6 class="card-title mb-1">
                                                    <a href="{{ url_for('view_book', book_id=book.id) }}" class="text-decoration-none text-dark">
                                                        {{ book.title }}
                                                    </a>
                                                </h6>
                                                <small class="text-muted d-block mb-2">{{ book.author }}</small>
                                                <div class="mt-auto d-flex justify-content-between align-items-center">
                                                    <span class="badge bg-light text-dark">
                                                        <i class="fas fa-eye"></i> {{ book.views }}
                                                    </span>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="{{ url_for('view_book', book_id=book.id) }}" class="btn btn-outline-primary btn-sm" title="查看详情">
                                                            <i class="fas fa-book-open"></i>
                                                        </a>
                                                        <button class="btn btn-outline-danger btn-sm favorite-btn" data-book-id="{{ book.id }}" title="取消收藏">
                                                            <i class="fas fa-heart"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="text-center py-4">
                                <i class="fas fa-heart-broken fa-3x text-muted mb-3"></i>
                                <h5>您还没有收藏图书</h5>
                                <p class="text-muted">浏览图书库并收藏您喜欢的图书</p>
                                <a href="{{ url_for('books') }}" class="btn btn-primary mt-2">
                                    <i class="fas fa-search me-2"></i>浏览图书
                                </a>
                            </div>
                            {% endif %}
                        </div>
                        
                        <!-- 收藏的帖子 Tab -->
                        <div class="tab-pane fade" id="favoritePosts" role="tabpanel" aria-labelledby="favorite-posts-tab">
                            {% if favorite_posts %}
                                {% for post in favorite_posts %}
                                <div class="card ink-card mb-3 post-card">
                                    <div class="card-body">
                                        <div class="d-flex">
                                            <!-- 作者头像 -->
                                            <div class="me-3 flex-shrink-0">
                                                {% if post.author.avatar and post.author.avatar != 'default.png' %}
                                                <img src="{{ url_for('static', filename='avatars/' + post.author.avatar) }}" 
                                                     class="user-avatar-small" alt="{{ post.author.username }}"
                                                     onerror="handleImageError(this)">
                                                {% else %}
                                                <div class="default-avatar-small">{{ post.author.username[0]|upper }}</div>
                                                {% endif %}
                                            </div>
                                            
                                            <!-- 帖子内容 -->
                                            <div class="flex-grow-1">
                                                <div class="d-flex justify-content-between align-items-start mb-2">
                                                    <h6 class="card-title mb-0">
                                                        <a href="{{ url_for('view_post', post_id=post.id) }}" class="text-decoration-none">
                                                            {{ post.title }}
                                                        </a>
                                                    </h6>
                                                    {% if post.circle %}
                                                    <span class="badge bg-primary">
                                                        <i class="fas fa-users me-1"></i>{{ post.circle.name }}
                                                    </span>
                                                    {% endif %}
                                                </div>
                                                
                                                <div class="post-meta mb-1">
                                                    <small class="text-muted">
                                                        <i class="fas fa-user me-1"></i>{{ post.author.username }} · 
                                                        <i class="fas fa-clock me-1"></i>{{ post.created_at.strftime('%Y-%m-%d %H:%M') }}
                                                    </small>
                                                </div>
                                                
                                                <div class="post-content mb-2">
                                                    {{ post.content|striptags|truncate(100) }}
                                                </div>
                                                
                                                <div class="post-actions">
                                                    <a href="{{ url_for('view_post', post_id=post.id) }}" class="btn btn-sm btn-outline-primary" title="查看详情">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-danger favorite-post-btn" data-post-id="{{ post.id }}" title="取消收藏">
                                                        <i class="fas fa-bookmark"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                                
                                {% if more_favorite_posts %}
                                <div class="text-center mt-3">
                                    <a href="{{ url_for('favorite_posts') }}" class="btn btn-outline-primary btn-sm">
                                        <i class="fas fa-list"></i> 查看全部收藏帖子
                                    </a>
                                </div>
                                {% endif %}
                            {% else %}
                                <div class="text-center py-4">
                                    <i class="fas fa-bookmark fa-3x text-muted mb-3"></i>
                                    <h5>您还没有收藏帖子</h5>
                                    <p class="text-muted">浏览论坛并收藏您喜欢的帖子</p>
                                    <a href="{{ url_for('forum') }}" class="btn btn-primary mt-2">
                                        <i class="fas fa-comments me-2"></i>浏览论坛
                                    </a>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 上传的图书 -->
            <div class="card ink-card">
                <div class="card-header ink-header">
                    <h5 class="mb-0">上传的图书</h5>
                </div>
                <div class="list-group list-group-flush">
                    {% for book in uploaded_books %}
                    <a href="{{ url_for('view_book', book_id=book.id) }}" class="list-group-item list-group-item-action">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-1">{{ book.title }}</h6>
                                <small class="text-muted">{{ book.author }}</small>
                            </div>
                            <span class="badge bg-primary rounded-pill">
                                <i class="fas fa-eye"></i> {{ book.views }}
                            </span>
                        </div>
                    </a>
                    {% else %}
                    <div class="list-group-item text-center text-muted">
                        暂无上传的图书
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Toast 容器，用于显示消息通知 -->
<div class="toast-container position-fixed bottom-0 end-0 p-3"></div>

{% block scripts %}
<script>
    function handleImageError(img) {
        img.onerror = null;  // 防止循环
        img.src = "{{ url_for('static', filename='images/default_cover.jpg') }}";
    }
    
    // 头像预览功能
    function previewAvatar(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            
            reader.onload = function(e) {
                document.getElementById('avatar-preview-image').setAttribute('src', e.target.result);
                document.getElementById('current-avatar').style.display = 'none';
                document.getElementById('avatar-preview-container').style.display = 'block';
            }
            
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    function cancelAvatarPreview() {
        document.getElementById('avatar-select').value = '';
        document.getElementById('current-avatar').style.display = 'block';
        document.getElementById('avatar-preview-container').style.display = 'none';
    }
    
    function confirmAvatarUpload() {
        // 将选择的文件从avatar-select复制到hidden表单
        var input = document.getElementById('avatar-select');
        var formInput = document.getElementById('avatar-input');
        
        if (input.files && input.files[0]) {
            // 创建一个新的FileList对象
            var dataTransfer = new DataTransfer();
            dataTransfer.items.add(input.files[0]);
            formInput.files = dataTransfer.files;
            
            // 提交表单
            document.getElementById('avatar-form').submit();
        }
    }
    
    // 通知相关功能
    document.addEventListener('DOMContentLoaded', function() {
        // 标记所有通知为已读
        document.getElementById('mark-all-read-btn').addEventListener('click', function() {
            fetch('/notifications/mark-read', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.querySelectorAll('.notification-item').forEach(function(item) {
                        item.classList.remove('list-group-item-primary');
                    });
                }
            });
        });
        
        // 通知点击跳转
        document.querySelectorAll('.notification-item').forEach(function(item) {
            if (!item.querySelector('.btn-group')) { // 如果没有操作按钮
                item.addEventListener('click', function() {
                    var id = this.getAttribute('data-notification-id');
                    window.location.href = '/notification/' + id + '/view';
                });
            }
        });
        
        // 为所有图书收藏按钮添加点击事件监听器
        document.querySelectorAll('.favorite-btn').forEach(function(btn) {
            btn.addEventListener('click', function(event) {
                event.preventDefault();
                const bookId = this.getAttribute('data-book-id');
                const bookCard = this.closest('.col');
                toggleFavoriteBook(bookId, this, bookCard);
            });
        });
        
        // 为所有帖子收藏按钮添加点击事件监听器
        document.querySelectorAll('.favorite-post-btn').forEach(function(btn) {
            btn.addEventListener('click', function(event) {
                event.preventDefault();
                const postId = this.getAttribute('data-post-id');
                const postCard = this.closest('.post-card');
                toggleFavoritePost(postId, this, postCard);
            });
        });
    });
    
    // 切换图书收藏状态
    function toggleFavoriteBook(bookId, button, bookCard) {
        fetch(`/book/${bookId}/favorite`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            // 在个人主页上，取消收藏应该移除卡片
            if (data.action === 'unfavorited') {
                if (bookCard) {
                    // 平滑移除卡片
                    bookCard.style.transition = 'all 0.3s ease';
                    bookCard.style.opacity = '0';
                    bookCard.style.transform = 'scale(0.8)';
                    
                    setTimeout(() => {
                        bookCard.remove();
                        
                        // 检查是否还有收藏的书籍
                        const remainingBooks = document.querySelectorAll('#favoriteBooks .book-card');
                        if (remainingBooks.length === 0) {
                            // 如果没有书籍了，显示空状态
                            document.querySelector('#favoriteBooks .card-body').innerHTML = `
                                <div class="text-center py-4">
                                    <i class="fas fa-heart-broken fa-3x text-muted mb-3"></i>
                                    <h5>您还没有收藏图书</h5>
                                    <p class="text-muted">浏览图书库并收藏您喜欢的图书</p>
                                    <a href="{{ url_for('books') }}" class="btn btn-primary mt-2">
                                        <i class="fas fa-search me-2"></i>浏览图书
                                    </a>
                                </div>
                            `;
                        }
                    }, 300);
                }
                showToast('已取消收藏', '图书已从您的收藏中移除');
            }
        })
        .catch(error => console.error('Error:', error));
    }
    
    // 切换帖子收藏状态
    function toggleFavoritePost(postId, button, postCard) {
        fetch(`/post/${postId}/favorite`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                if (data.action === 'unfavorited') {
                    // 从收藏列表中移除帖子
                    postCard.style.transition = 'all 0.3s ease';
                    postCard.style.opacity = '0';
                    postCard.style.transform = 'scale(0.8)';
                    
                    setTimeout(() => {
                        postCard.remove();
                        
                        // 检查是否还有收藏的帖子
                        const remainingPosts = document.querySelectorAll('#favoritePosts .post-card');
                        if (remainingPosts.length === 0) {
                            // 如果没有帖子了，显示空状态
                            document.querySelector('#favoritePosts .card-body').innerHTML = `
                                <div class="text-center py-4">
                                    <i class="fas fa-bookmark fa-3x text-muted mb-3"></i>
                                    <h5>您还没有收藏帖子</h5>
                                    <p class="text-muted">浏览论坛并收藏您喜欢的帖子</p>
                                    <a href="{{ url_for('forum') }}" class="btn btn-primary mt-2">
                                        <i class="fas fa-comments me-2"></i>浏览论坛
                                    </a>
                                </div>
                            `;
                        }
                    }, 300);
                    
                    showToast('取消收藏', '帖子已从您的收藏中移除');
                }
            } else {
                showToast('操作失败', data.message || '请稍后重试', 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('操作失败', '请稍后重试', 'danger');
        });
    }
    
    // 显示提示信息
    function showToast(title, message, type = 'primary') {
        try {
            // 检查 bootstrap 对象是否存在
            if (typeof bootstrap === 'undefined') {
                console.error('Bootstrap not loaded');
                alert(title + ': ' + message);
                return;
            }
            
            // 创建toast元素
            const toastEl = document.createElement('div');
            toastEl.className = 'toast align-items-center text-white bg-' + type + ' border-0';
            toastEl.setAttribute('role', 'alert');
            toastEl.setAttribute('aria-live', 'assertive');
            toastEl.setAttribute('aria-atomic', 'true');
            
            // 设置自动隐藏
            toastEl.setAttribute('data-bs-delay', '3000');
            
            // 添加内容
            toastEl.innerHTML = 
                '<div class="d-flex">' +
                    '<div class="toast-body">' +
                        '<strong>' + title + '</strong>: ' + message +
                    '</div>' +
                    '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>' +
                '</div>';
            
            // 添加到页面
            const toastContainer = document.querySelector('.toast-container');
            if (toastContainer) {
                toastContainer.appendChild(toastEl);
            } else {
                // 如果不存在容器则创建
                const newContainer = document.createElement('div');
                newContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
                newContainer.appendChild(toastEl);
                document.body.appendChild(newContainer);
            }
            
            // 显示toast
            const toast = new bootstrap.Toast(toastEl);
            toast.show();
        } catch (error) {
            console.error('Error showing toast:', error);
            alert(title + ': ' + message);
        }
    }
</script>
{% endblock %}
{% endblock %} 